import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { login as loginApi, logout as logoutApi, getCurrentUser } from '@/api/user'
import type { User, UserLoginRequest } from '@/types'
import { UserType } from '@/types'
import router from '@/router'

export const useUserStore = defineStore(
  'user',
  () => {
    // 状态
    const userInfo = ref<User | null>(null)
    const loading = ref(false)

    // 计算属性
    const isLoggedIn = computed(() => !!userInfo.value)
    const userRole = computed(() => userInfo.value?.userType)
    const isStudent = computed(() => userRole.value === UserType.STUDENT)
    const isRepairWorker = computed(() => userRole.value === UserType.REPAIR_WORKER)
    const isAdmin = computed(() => userRole.value === UserType.ADMIN)

    // 权限检查
    const hasRole = (roles: UserType[]): boolean => {
      return userRole.value ? roles.includes(userRole.value) : false
    }

    // 登录
    const login = async (loginData: UserLoginRequest): Promise<boolean> => {
      try {
        loading.value = true

        const response = await loginApi(loginData)

        if (response.code === 0 && response.data) {
          userInfo.value = response.data
          message.success('登录成功')

          // 跳转到仪表板 看一下当前地址是否有值
          const url = router.currentRoute.value.query.redirect
            ? (router.currentRoute.value.query.redirect as string)
            : '/dashboard'
          await router.push(url)
          return true
        } else {
          // 服务器返回了错误信息
          message.error(response.message || '登录失败')
          return false
        }
      } catch (error: any) {
        console.error('登录失败:', error)

        // 处理不同类型的错误
        if (error.response) {
          // HTTP 错误响应
          const { status, data } = error.response
          if (status === 401) {
            message.error('账号或密码错误')
          } else if (status === 403) {
            message.error('账号已被禁用，请联系管理员')
          } else if (data?.message) {
            message.error(data.message)
          } else {
            message.error(`登录失败 (${status})`)
          }
        } else if (error.request) {
          // 网络错误
          message.error('网络连接失败，请检查网络连接')
        } else if (error.message) {
          // 其他错误
          message.error(error.message)
        } else {
          message.error('登录失败，请稍后重试')
        }
        return false
      } finally {
        loading.value = false
      }
    }

    // 清除用户状态
    const clearUserState = async (): Promise<void> => {
      // 清除本地状态
      userInfo.value = null

      // 清除持久化存储
      localStorage.removeItem('user-store')

      // 清除cookie
      document.cookie = 'SESSION=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'

      // 跳转到登录页
      const fullPath = router.currentRoute.value.fullPath
      let nextUrl = '/login'
      if (!fullPath.match(/^\/(login|register)(\?|$)/)) {
        nextUrl = '/login?redirect=' + encodeURIComponent(fullPath)
      }
      await router.push(nextUrl)
    }

    // 注销
    const logout = async (isManualLogout?: boolean): Promise<void> => {
      try {
        await logoutApi()
      } catch (error: unknown) {
        console.error('注销请求失败:', error)
      } finally {
        // 无论请求是否成功，都清除本地状态
        // 使用cookie+session，服务器会清除cookie
        userInfo.value = null

        // 清除持久化存储
        localStorage.removeItem('user-store')

        // 如果是手动退出，显示成功消息并跳转到登录页
        if (isManualLogout) {
          message.success('已退出登录')
          await router.push('/login')
        } else {
          // 自动退出（如session过期），直接跳转
          const fullPath = router.currentRoute.value.fullPath
          let nextUrl = '/login'
          if (!fullPath.match(/^\/(login|register)(\?|$)/)) {
            nextUrl = '/login?redirect=' + encodeURIComponent(fullPath)
          }
          await router.push(nextUrl)
        }

        // 清除cookie
        document.cookie = 'SESSION=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'
      }
    }

    // 获取用户信息
    const fetchUserInfo = async (): Promise<boolean> => {
      try {
        const response = await getCurrentUser()
        if (response.code === 0 && response.data) {
          userInfo.value = response.data
          return true
        }
        return false
      } catch (error: unknown) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，可能是session过期，清除登录状态
        userInfo.value = null
        return false
      }
    }

    // 初始化用户状态
    const initUserState = async (): Promise<void> => {
      // 尝试获取用户信息，如果有有效的session，服务器会返回用户信息
      await fetchUserInfo()
    }

    return {
      // 状态
      userInfo,
      loading,

      // 计算属性
      isLoggedIn,
      userRole,
      isStudent,
      isRepairWorker,
      isAdmin,

      // 方法
      hasRole,
      login,
      logout,
      clearUserState,
      fetchUserInfo,
      initUserState,
    }
  },
  {
    persist: {
      key: 'user-store',
      storage: localStorage,
      // @ts-expect-error - pinia-plugin-persistedstate 类型定义问题
      paths: ['userInfo'], // 只持久化用户信息，不持久化 loading 状态
    },
  },
)
